package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.BeautyPhotoActivity;
import com.linewow.xhyy.nihaonew.activity.ConfigureActivity;
import com.linewow.xhyy.nihaonew.activity.FollowFanActivity;
import com.linewow.xhyy.nihaonew.activity.user.SignActivity;
import com.linewow.xhyy.nihaonew.adapter.NihaoVPAdapter;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseEntity;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.detail.MineInfo;
import com.linewow.xhyy.nihaonew.entity.user.UserInfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.helper.VoiceMenuHelper;
import com.linewow.xhyy.nihaonew.model.AppConstants;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.util.CommonUtil;
import com.linewow.xhyy.nihaonew.util.Help;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.linewow.xhyy.nihaonew.view.BlurredLayout;
import com.linewow.xhyy.nihaonew.view.VoiceButton2White;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by LXR on 2016/10/10.
 */
public class MineMainFragment extends BaseFragment {
    @Bind(R.id.mine_main_bg_img)
    ImageView mineMainBgImg;
    @Bind(R.id.mine_main_blurred)
    BlurredLayout mineMainBlurred;
    @Bind(R.id.widget_mine_configure)
    ImageView widgetMineConfigure;
    @Bind(R.id.widget_mine_avatar)
    ImageView widgetMineAvatar;
    @Bind(R.id.widget_mine_edit_profile)
    RelativeLayout widgetMineEditProfile;
    @Bind(R.id.widget_mine_edit_recorder)
    RelativeLayout widgetMineEditRecorder;
    @Bind(R.id.widget_mine_avatar_rela)
    RelativeLayout widgetMineAvatarRela;
    @Bind(R.id.widget_mine_sign_tv)
    TextView widgetMineSignTv;
    @Bind(R.id.widget_mine_voice_btn)
    VoiceButton2White widgetMineVoiceBtn;
    @Bind(R.id.widget_mine_attention_num)
    TextView widgetMineAttentionNum;
    @Bind(R.id.widget_mine_attention_tv)
    TextView widgetMineAttentionTv;
    @Bind(R.id.widget_mine_fans_num)
    TextView widgetMineFansNum;
    @Bind(R.id.widget_mine_fans_tv)
    TextView widgetMineFansTv;
    @Bind(R.id.widget_mine_like_num)
    TextView widgetMineLikeNum;
    @Bind(R.id.widget_mine_like_tv)
    TextView widgetMineLikeTv;
    @Bind(R.id.mine_main_toolbar)
    Toolbar mineMainToolbar;
    @Bind(R.id.mine_main_tabs)
    TabLayout mineMainTabs;
    @Bind(R.id.mine_main_toolbar_layout)
    CollapsingToolbarLayout mineMainToolbarLayout;
    @Bind(R.id.mine_main_appbar)
    AppBarLayout mineMainAppbar;
    @Bind(R.id.mine_main_viewpager)
    ViewPager mineMainViewpager;
    @Bind(R.id.widget_mine_bottom_line)
    LinearLayout widgetMineBottomLine;
    @Bind(R.id.widget_mine_location_tv)
    TextView widgetMineLocationTv;
    @Bind(R.id.widget_mine_gender_img)
    ImageView widgetMineGenderImg;
    @Bind(R.id.widget_mine_location_relative)
    RelativeLayout widgetMineLocationRelative;
    @Bind(R.id.widget_mine_still_nick)
    TextView widgetMineStillNick;
    @Bind(R.id.mine_main_blurred_view)
    View mineMainBlurredView;
    private String TAG = "MineMainFragment";
    private Gson gson;
    private Type mineInfoType;
    private NiHaoHelper niHaoHelper;
    private VoiceMenuHelper voiceMenuHelper;
    private MinePhotoFragment minePhotoFragment;
    private MineTopicFragment mineTopicFragment;
    private NihaoVPAdapter nihaoVPAdapter;

    private UserInfo userInfo;

    private View viewPhoto, viewTopic;
    private TextView photoNum, topicNum, photoName, topicName;
    private ImageView photoImg, topicImg;

    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_mine_main, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        voiceMenuHelper = new VoiceMenuHelper(MineMainFragment.this.getActivity(), widgetMineConfigure, TAG);
        initTabLayout();
        EventBus.getDefault().register(MineMainFragment.this);
        niHaoHelper = NiHaoHelper.getInstance();
        UserInfo storeInfo = niHaoHelper.getUserProfile();
        if (storeInfo != null) {
            updateViewBy(storeInfo);
        }
    }

    /**
     * 初始化  toolbarlayout
     */
    public void initTabLayout() {
        mineMainToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.color_0));
        mineMainToolbarLayout.setContentScrimColor(getResources().getColor(R.color.colorPrimary));
        mineMainToolbarLayout.setStatusBarScrimColor(getResources().getColor(R.color.colorPrimary));
        mineMainToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.color_0));
        mineMainToolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.color_0));
        mineMainToolbarLayout.setTitle(getString(R.string.title_mine));
        mineMainBlurred.setBlurRadius(0, 50);
        setupViewPager(mineMainViewpager);
        mineMainTabs.setupWithViewPager(mineMainViewpager);
        initTitleView();
    }

    private void initGson() {
        gson = new Gson();
        mineInfoType = new TypeToken<BaseEntity<MineInfo<UserInfo>>>() {
        }.getType();
    }

    private void initTitleView() {
        viewPhoto = View.inflate(MineMainFragment.this.getActivity(), R.layout.item_title, null);
        viewTopic = View.inflate(MineMainFragment.this.getActivity(), R.layout.item_title, null);
        photoImg = (ImageView) viewPhoto.findViewById(R.id.item_title_img);
        topicImg = (ImageView) viewTopic.findViewById(R.id.item_title_img);
        photoName = (TextView) viewPhoto.findViewById(R.id.item_title_tv);
        photoNum = (TextView) viewPhoto.findViewById(R.id.item_title_num);
        topicName = (TextView) viewTopic.findViewById(R.id.item_title_tv);
        topicNum = (TextView) viewTopic.findViewById(R.id.item_title_num);
        topicImg.setImageResource(R.mipmap.icon_topic);
        topicName.setText(getString(R.string.widget_topic));
        TabLayout.Tab tagPhoto = mineMainTabs.getTabAt(0);
        tagPhoto.setCustomView(viewPhoto);
        TabLayout.Tab tabTopic = mineMainTabs.getTabAt(1);
        tabTopic.setCustomView(viewTopic);
    }


    private void setupViewPager(ViewPager mineMainViewpager) {
        nihaoVPAdapter = new NihaoVPAdapter(getFragmentManager());
        minePhotoFragment = new MinePhotoFragment();
        mineTopicFragment = new MineTopicFragment();
        nihaoVPAdapter.addFragment(minePhotoFragment, getString(R.string.widget_photo));
        nihaoVPAdapter.addFragment(mineTopicFragment, getString(R.string.widget_topic));
        mineMainViewpager.setAdapter(nihaoVPAdapter);
    }


    @Override
    public void initList() {
        super.initList();
        initGson();
        requestInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void requestInfo() {
        OkHttpUtils.get()
                .url("https://m.en1on1.com/api/api1.5/homepage.php?ac=homepage&token=" + NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                        Log.e(TAG, "错误了" + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        BaseEntity<MineInfo<UserInfo>> baseEntity = gson.fromJson(response, mineInfoType);
                        UserInfo userInfo = baseEntity.data.userinfo;
                        Log.e(TAG, "昵称" + baseEntity.data.userinfo.nickname);
                        Log.e(TAG, "len" + baseEntity.data.userinfo.len);

                        niHaoHelper.saveProfile(userInfo);
                        MineMainFragment.this.userInfo = userInfo;
                        Log.e(TAG, "请求完成6");
                        updateViewBy(userInfo);

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG, "销毁的时候存储");

        ButterKnife.unbind(this);
    }

    @OnClick({R.id.widget_mine_configure,
            R.id.widget_mine_avatar,
            R.id.widget_mine_edit_profile,
            R.id.widget_mine_edit_recorder,
            R.id.widget_mine_attention_rela,
            R.id.widget_mine_sign_tv,
            R.id.widget_mine_fans_rela})
    public void onClick(View view) {

        int id = view.getId();
        switch (id) {
            case R.id.widget_mine_avatar:
                if (userInfo != null) {
                    startBeautyPhotoActivity();
                }
                break;
            case R.id.widget_mine_configure:
            case R.id.widget_mine_edit_profile:
                Intent intent = new Intent(getActivity(), ConfigureActivity.class);//设置界面
                startActivityForResult(intent, AppConstants.CONFIGURECODE);
                break;
            case R.id.widget_mine_edit_recorder:
                voiceMenuHelper.show();
                break;

            case R.id.widget_mine_attention_rela:
                Intent intent1 = new Intent(getActivity(), FollowFanActivity.class);
                intent1.putExtra("flag", false);
                startActivity(intent1);

                break;
            case R.id.widget_mine_fans_rela:
                Intent intent2 = new Intent(getActivity(), FollowFanActivity.class);
                intent2.putExtra("flag", true);
                startActivity(intent2);

                break;
            case R.id.widget_mine_sign_tv:
                Intent signIntent = new Intent(getActivity(), SignActivity.class);
//                signIntent.putExtras("",);
                signIntent.putExtra("info", widgetMineSignTv.getText().toString());
                startActivityForResult(signIntent, AppConstants.CONFIGURECODE);
                break;
        }

    }


    private void updateViewBy(UserInfo userInfo) {
//        mineMainToolbarLayout.setTitle(userInfo.nickname);
        widgetMineStillNick.setText(userInfo.nickname);
        if (userInfo.gender.equals("0")) {
            widgetMineGenderImg.setVisibility(View.GONE);
        } else if (userInfo.gender.equals("1")) {
            widgetMineGenderImg.setImageResource(R.mipmap.icon_gender_male);
        } else {
            widgetMineGenderImg.setImageResource(R.mipmap.icon_gender_female);
        }

        widgetMineAttentionNum.setText(userInfo.follow);
        widgetMineFansNum.setText(userInfo.fans);
        widgetMineLikeNum.setText(userInfo.up);
        if (userInfo.country != null) {
            widgetMineLocationTv.setText(userInfo.country);
        } else {
            widgetMineLocationTv.setText(getString(R.string.message_no_area));
        }

        if (!userInfo.sig_txt.equals("null")) {
            widgetMineSignTv.setText(userInfo.sig_txt);
        } else {
            widgetMineSignTv.setText(getString(R.string.message_edit_sign));
        }

        Picasso.with(MineMainFragment.this.getActivity()).load(userInfo.head_img).error(R.mipmap.err_avatar).fit().into(widgetMineAvatar);
        if (!userInfo.head_img.endsWith(AppConstants.NOAVATAR)) {
            mineMainBlurredView.setVisibility(View.VISIBLE);
            Picasso.with(MineMainFragment.this.getActivity()).load(userInfo.head_img).error(R.mipmap.delete3).fit().into(mineMainBgImg);
        } else {
            Log.e(TAG, "设置背景为空");
            mineMainBgImg.setImageBitmap(null);
            mineMainBlurredView.setVisibility(View.INVISIBLE);
        }


        if (userInfo.audiopath.equals("")) {
            widgetMineVoiceBtn.setVisibility(View.GONE);
        } else {
            widgetMineVoiceBtn.setVisibility(View.VISIBLE);
        }

        if (userInfo.sig_audiotime.equals("0")) {
            widgetMineVoiceBtn.setVisibility(View.GONE);
        } else {
            widgetMineVoiceBtn.setVisibility(View.VISIBLE);

            widgetMineVoiceBtn.setUrlPath(userInfo.sig_audiotime, userInfo.audiopath);
        }
//        nihaoVPAdapter.setFirstTitle(getString(R.string.widget_photo)+" "+userInfo.photonum);
//        nihaoVPAdapter.setSecondTitle(getString(R.string.widget_topic)+" "+userInfo.threadnum);

        photoNum.setText(userInfo.photonum);
        topicNum.setText(userInfo.threadnum);
    }


    @Subscriber(tag = "MineMainFragment", mode = ThreadMode.MAIN)
    public void onVoiceChoose(MessageEvent messageEvent) {
        String path = messageEvent.getMessage();
        Log.e(TAG, "路径" + path);
        String length = CommonUtil.getLength(path);
        Log.e(TAG, "长度" + length);
        uploadSignVoice(path, length);
    }

    private void uploadSignVoice(String path, String length) {
        Log.e(TAG, "录音地址" + path);

        showLoading();
        PostFormBuilder builder = OkHttpUtils.post();
        Map<String, String> map = new HashMap<String, String>();
        map.put("audiotime", "" + length);
        builder.addFile("audio", path, new File(path));
        builder.url(HttpModel.UPDATESIGNVOICE + NiHaoApp.token)
                .params(map)
                .build()
                .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {

                    @Override
                    public void onError(Call call, Exception e, int id) {

                        Log.e(TAG, "错误信息" + e.getMessage());
                    }

                    @Override
                    public void onResponse(NiHaoEntity response, int id) {
                        Log.e(TAG, "得到response-->" + response);
                        if (response.status) {
                            requestInfo();
                            dismissLoading();
                        }
                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(MineMainFragment.this);
    }


    @Subscriber(tag = "login", mode = ThreadMode.POST)
    public void getLoginMessageEvent(MessageEvent messageEvent) {
        Log.e(TAG, "登录了");
        requestInfo();
        minePhotoFragment.refreshData();
        mineTopicFragment.refreshData();
    }

    @Subscriber(tag = "refresh", mode = ThreadMode.MAIN)
    public void refreshMessage(MessageEvent messageEvent) {
        Log.e(TAG, "刷新了");
        requestInfo();
        minePhotoFragment.refreshData();
        mineTopicFragment.refreshData();
    }

    @Subscriber(tag = "logout", mode = ThreadMode.POST)
    public void getLogOutMessageEvent(MessageEvent messageEvent) {
        Log.e(TAG, "退出了");

    }

    @Subscriber(tag = "NewCommitActivity", mode = ThreadMode.POST)
    public void getNewCommitMessageEvent(MessageEvent messageEvent) {
        requestInfo();
        Log.e(TAG, "通知照片和话题刷新了");
        minePhotoFragment.refreshData();
        mineTopicFragment.refreshData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstants.CONFIGURECODE && resultCode == AppConstants.CONFIGURECODE) {
            Log.e(TAG, "再次刷新");
            requestInfo();
        }
    }


    public void startBeautyPhotoActivity() {
        Intent intent = new Intent(MineMainFragment.this.getActivity(), BeautyPhotoActivity.class);
        intent.putExtra("uri", userInfo.head_img);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            final Pair<View, String>[] pairs = Help.createSafeTransitionParticipants
                    (MineMainFragment.this.getActivity(), false, new Pair<>(widgetMineAvatar, "beauty"));
            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MineMainFragment.this.getActivity(), pairs);
            startActivity(intent, options.toBundle());
        } else {
            startActivity(intent);
        }
    }

}
